package org.lztvn.elearning.controllers;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.lztvn.elearning.entities.Product;
import org.lztvn.elearning.entities.Friend;
import org.lztvn.elearning.entities.Message;
import org.lztvn.elearning.entities.User;
import org.lztvn.elearning.service.IFriendService;
import org.lztvn.elearning.service.IMessageService;
import org.lztvn.elearning.service.IUserService;
import org.lztvn.elearning.socket.LZTUserManager;
import org.lztvn.elearning.unityclass.CommonObj;
import org.lztvn.elearning.unityclass.LoginForm;
import org.lztvn.elearning.unityclass.MessageUnity;
import org.lztvn.elearning.unityclass.RegisterForm;
import org.lztvn.elearning.unityclass.RequestFriendUnity;
import org.lztvn.elearning.unityclass.RoleLZT;
import org.lztvn.elearning.unityclass.UserOutDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.apache.commons.validator.routines.EmailValidator;

import com.mysql.jdbc.StringUtils;

@Controller
@SessionAttributes("userFLogin")
@Scope("session")
public class LztUserController extends AppController implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Autowired
	IUserService userService;
	@Autowired
	IMessageService messageService;
	@Autowired
	IFriendService friendService;
	public LztUserController(){
		Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
		//List<Integer> lst = new ArrayList<Integer>();
		//lst.add(RoleLZT.Admin.getValue());lst.add(RoleLZT.Student.getValue());lst.add(RoleLZT.Teacher.getValue());lst.add(RoleLZT.User.getValue());
		/*begin role for action home*/
		//map.put("mypage", lst);
		/*end*/
		/*begin role for action home*/
		//map.put("sendMessage", lst);
		//map.put("addFriend", lst);
		/*end*/
		this.roles = map;
	}
	@RequestMapping(value="/mypage",method=RequestMethod.GET)
	public String mypage(Locale locale, Model model){
		if(model.asMap().get("lzt-user")!=null){  
			User user=(User)model.asMap().get("lzt-user");   
			List<User> lstUser = userService.getAllUserExceptMe(user);
			List<Message> lstMessage = userService.getMessageNotifyToMe(user);
			model.addAttribute("lstUser", lstUser);
			model.addAttribute("lstMessage",lstMessage);
		}  
		return "myapp.mypage";
	}
	@RequestMapping(value="/sendMessage", method=RequestMethod.POST,produces="application/json",consumes="application/json")
	@ResponseBody
	public  Boolean sendMessage(@RequestBody MessageUnity message,Model model) {	
		if(model.asMap().get("userFLogin")!=null){  
			User user=(User)model.asMap().get("userFLogin");   
			if(message.getMessage()!=null && message.getMessage()!=""){
				Message mes = new Message(user.getIdUser(),Long.valueOf(message.getToUser()).longValue(), message.getMessage());
				messageService.addMessage(mes);
				message.setFromUser(String.valueOf(user.getIdUser()));
				LZTUserManager.getInstance().sendMessage(message);
				return true;
			}

		}  
		return false;			
	}
	@RequestMapping(value="/getAllUser", method=RequestMethod.POST,produces="application/json",consumes="application/json")
	@ResponseBody
	public  Object getAllUser(Model model) {	
		List<UserOutDC> lst= new ArrayList<UserOutDC>();
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin");   
			List<User> lstUser = new ArrayList<User>();
			lstUser = userService.getAllUserExceptMe(user);
			for (User usr : lstUser) {
				UserOutDC item = new UserOutDC();
				item.setId(usr.getIdUser());
				item.setName(usr.getFirstName());
				lst.add(item);
			}
			return lst;
		}  
		return null;			
	}

	@RequestMapping(value="/friendNotify", method=RequestMethod.GET,produces="application/json")
	@ResponseBody
	public  Object friendNotify(Model model) {	
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin");   
			return friendService.getAllRequestFriend(user);
		}
		return null;			
	}

	@RequestMapping(value="/ajaxLogin", method=RequestMethod.POST,produces="application/json")
	@ResponseBody
	public  Object Login(@RequestBody LoginForm object,Model model,HttpServletRequest request) {	

		Map<String,Map<String,String>> result = new HashMap<String,Map<String,String>>();
		if(StringUtils.isNullOrEmpty(object.getUsername())||StringUtils.isNullOrEmpty(object.getPassword())){
			Map<String,String> error = new HashMap<String, String>();
			if(StringUtils.isNullOrEmpty(object.getUsername())){				
				error.put("username", "blank");
			}
			if(StringUtils.isNullOrEmpty(object.getPassword())){
				error.put("password", "blank");
			}
			result.put("error", error);
		}else{ 
			if(userService.login(object.getUsername(), object.getPassword()).size() > 0) {
				result.put("success", new HashMap<String, String>());
				User u = userService.getUserByUsername(object.getUsername());
				request.getSession().setAttribute("userFLogin", u);
			} else {
				Map<String,String> error = new HashMap<String, String>();
				error.put("username", "blank");
				error.put("password", "blank");
				result.put("error", error);
			}		
		}
		return result;
	}

	@RequestMapping(value="/ajaxRegister", method=RequestMethod.POST,produces="application/json")
	@ResponseBody
	public  Object register(@RequestBody RegisterForm object,Model model,HttpServletRequest request) {	

		Map<String,Map<String,String>> result = new HashMap<String,Map<String,String>>();
		if(StringUtils.isNullOrEmpty(object.getUsername())||StringUtils.isNullOrEmpty(object.getPassword())||StringUtils.isNullOrEmpty(object.getRetypepass())||StringUtils.isNullOrEmpty(object.getCheckPrivacy())||!EmailValidator.getInstance(true).isValid(object.getEmail())||(!object.getPassword().equals(object.getRetypepass()))){
			Map<String,String> error = new HashMap<String, String>();
			if(StringUtils.isNullOrEmpty(object.getUsername())){				
				error.put("username", "blank");
			}
			if(StringUtils.isNullOrEmpty(object.getPassword())){
				error.put("password", "blank");
			}
			if(StringUtils.isNullOrEmpty(object.getRetypepass())||!object.getPassword().equals(object.getRetypepass())){
				error.put("retypepass", "blank");
			}
			if(StringUtils.isNullOrEmpty(object.getCheckPrivacy())){
				error.put("checkPrivacy", "blank");
			}
			if(!EmailValidator.getInstance(true).isValid(object.getEmail())){
				error.put("email", "blank");
			}
			result.put("error", error);
		}else{ 
			User findUser = userService.getUserByUsername(object.getUsername());
			Map<String,String> error = new HashMap<String, String>();
			if(findUser!=null){
				error.put("username", "blank");
				result.put("error", error);
			}else if(userService.getUserByEmail(object.getEmail())!=null){
				error.put("email", "blank");
				result.put("error", error);
			}else{
				result.put("success", new HashMap<String, String>());
				User u = new User();
				u.setUsername(object.getUsername());
				u.setEmail(object.getEmail());
				u.setPassword(object.getPassword());
				u.setAddress("unset");
				u.setFirstName("unset");
				u.setLastName("unset");
				userService.addUser(u);
				request.getSession().setAttribute("userFLogin", u);
				//User u = userService.getUserByUsername(object.getUsername());
				//model.addAttribute("userFLogin", u);
				//request.getSession().setAttribute("userFLogin", u);
			}
		
		}
		return result;
	}

	@RequestMapping(value="/mesageNotify", method=RequestMethod.GET,produces="application/json")
	@ResponseBody
	public  Object mesageNotify(Model model) {	
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin");   
			return friendService.getAllMessage(user);
		}
		return null;			
	}

	@RequestMapping(value="/getAllMessage", method=RequestMethod.POST,produces="application/json")
	@ResponseBody
	public  Object getAllMessage(@RequestBody RequestFriendUnity friend, Model model) {	
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin"); 
			friend.setFromUser(friend.getIdFriend());
			friend.setToUser(user.getIdUser().toString());
			friendService.setAllMessageToRead(friend);
			return friendService.getAllMessageFromTo(friend);
		}
		return null;			
	}

	@RequestMapping(value="/addFriend", method=RequestMethod.POST,produces="application/json")
	@ResponseBody
	public  Object addFriend(@RequestBody RequestFriendUnity friend,Model model) {	
		Friend friendTemplate = new Friend();
		friendTemplate.setToUser(Long.parseLong(friend.getToUser()));
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin");   
			friendTemplate.setFromUser(user.getIdUser());
			LZTUserManager.getInstance().NotifyFriendRequest(friendTemplate);
		}
		friendService.addFriend(friendTemplate);
		CommonObj obj =  new CommonObj();
		obj.success = true;
		return obj;			
	}

	@RequestMapping(value="/hasCheck", method=RequestMethod.POST,produces="application/json",consumes="application/json")
	@ResponseBody
	public  Object hasCheck(@RequestBody RequestFriendUnity friend,Model model) {	
		Friend friendTemplate = new Friend();
		friendTemplate.setFromUser(Long.parseLong(friend.getIdFriend()));
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin");   
			friendTemplate.setToUser(user.getIdUser());
		}
		friendService.changeRequestFriendToChecked(friendTemplate);
		CommonObj obj =  new CommonObj();
		obj.success = true;
		return obj;			
	}

	@RequestMapping(value="/confirm", method=RequestMethod.POST,produces="application/json",consumes="application/json")
	@ResponseBody
	public  Object confirm(@RequestBody RequestFriendUnity friend,Model model) {	
		Friend friendTemplate = new Friend();
		friendTemplate.setFromUser(Long.parseLong(friend.getIdFriend()));
		if(model.asMap().get("userFLogin")!=null){  
			User user=  (User) model.asMap().get("userFLogin");   
			friendTemplate.setToUser(user.getIdUser());
		}
		friendService.changeRequestFriendStatus(friendTemplate);
		CommonObj obj =  new CommonObj();
		obj.success = true;
		return obj;			
	}
}
